import React from 'react';

import { is } from 'immutable';

export class PureComponent extends React.Component {
  // 版本问题???
  shouldComponentUpdate(nextProps: any, nextState: any) {
    return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);
  }
}

export function memo(OldComponent: any) {
  return class extends PureComponent {
    render() {
      return <OldComponent {...this.props} />;
    }
  };
}

export function shallowEqual(obj1: any, obj2: any) {
  if (obj1 === obj2) return true;
  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false;
  }
  let keys1 = Object.keys(obj1);
  let keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  for (let key of keys1) {
    // 深度比较 但是性能特别的高
    if (!obj2.hasOwnProperty(key) || !is(obj1[key], obj2[key])) {
      return false;
    }
  }
  return true;
}
